#!/usr/bin/env python
import zmq
import pdb

class ZmqServer(object):
	ctx = None
	def __init__(self, sock_type, port):
		assert isinstance(port,str),"'port' must be a string."

		if ZmqServer.ctx==None:
			print("Create a zmq.Context.")
			ZmqServer.ctx = zmq.Context()

		self.ctx_ = ZmqServer.ctx
		self.sock_ = self.ctx_.socket(sock_type)
		addr = "tcp://*:{0}".format(port)
		print("Server bind to {0}.".format(addr))
		self.sock_.bind(addr)

	def send(self,msg):
		self.sock_.send(msg)

	def recv(self):
		return self.sock_.recv()


class ZmqClient(object):
	ctx = None
	def __init__(self,socktype,ip,port):
		if ZmqClient.ctx==None:
			print("Create a zmq.Context.")
			ZmqClient.ctx = zmq.Context()

		self.ip_ = ip
		self.port_ = port
		self.ctx_ = ZmqClient.ctx
		addr = "tcp://{0}:{1}".format(self.ip_,self.port_)
		self.sock_ = self.ctx_.socket(socktype)
		print("Client connect to {0}.".format(addr))
		#pdb.set_trace()
		self.sock_.connect(addr)

	def setFilter(self, filter=""):
		self.sock_.setsockopt(zmq.SUBSCRIBE,filter)

	def send(self, msg):
		self.sock_.send(msg)

	def recv(self):
		return self.sock_.recv()


class ZmqServerPub(ZmqServer):
	def __init__(self,port):
		super(ZmqServerPub,self).__init__(sock_type=zmq.PUB,port=port)

	def recv(self):
		pass

class ZmqServerRep(ZmqServer):
	def __init__(self,port):
		super(ZmqServerRep,self).__init__(sock_type=zmq.REP,port=port)

class ZmqClientSub(ZmqClient):
	def  __init__(self,ip,port):
		super(ZmqClientSub,self).__init__(socktype=zmq.SUB,ip=ip,port=port)

class ZmqClientReq(ZmqClient):
	def __init__(self,ip,port):
		super(ZmqClientReq,self).__init__(socktype=zmq.REQ,ip=ip,port=port)

